package com.ruoyi.report.utils;

import com.ruoyi.common.utils.file.FileUtils;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRGraphics2DExporter;
import net.sf.jasperreports.engine.export.JRGraphics2DExporterParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Base64;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @description JasperUtils
 */
public class JasperUtils {
    private static final Logger log = LoggerFactory.getLogger(JasperUtils.class);

    /**
     * 在线预览pdf
     */
    public static void preViewPdf(HttpServletResponse response,String tempPath,Map<String,Object> map) {

        try {
//            //获取文件流
//            ClassPathResource resource = new ClassPathResource(tempPath);
//            File file = resource.getFile();
//            log.info("file.getPath() = " + file.getPath());

//            int index = file.getPath().lastIndexOf('\\');
//            String path = file.getPath().substring(0,index+1);
//            String filename = file.getPath().substring(index+1);
//            int index1 = filename.lastIndexOf('.');
//            String newfilename = filename.substring(0,index1)+".jasper";
//            String newfile = path + newfilename;
//            JasperCompileManager.compileReportToFile(file.getPath(),newfile);
//            File file1 = new File(newfile);
//            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(file1);

//            this.getClass().getResourceAsStream("template/png/PASS.png")
//            new ByteArrayInputStream(org.apache.commons.codec.binary.Base64.decodeBase64($F{pic2}.getBytes()))

            //jar包这样读文件流。
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources(tempPath);
            Resource resource = resources[0];

            InputStream in = resource.getInputStream();
            JasperReport jasperReport = JasperCompileManager.compileReport(in);

            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map,new JREmptyDataSource() );
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "inline;");
            final OutputStream outputStream = response.getOutputStream();
            JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
            in.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * @Descriptionmap 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
     * @author
     * @Date
     * @param path 图片路径
     * @return
     */
    public static String imageToBase64(String path) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {

            //jar包这样读文件流。
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources(path);
            Resource resource = resources[0];

            InputStream in = resource.getInputStream();
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(data);// 返回Base64编码过的字节数组字符串
    }


    /**
     * 在线预览pdf 多页表单
     */
    public static void preViewPdfAndList(HttpServletResponse response, String tempPath, Map<String,Object> map, List list) {

        try {

            //jar包这样读文件流。
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources(tempPath);
            Resource resource = resources[0];

            InputStream in = resource.getInputStream();
            JasperReport jasperReport = JasperCompileManager.compileReport(in);

            JRDataSource dataSource = new JRBeanCollectionDataSource(list);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map,dataSource );
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "inline;");
            final OutputStream outputStream = response.getOutputStream();
            JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
            in.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 下载pdf
     */
    public static void downloadPdf(HttpServletResponse response,String tempPath,String fileName,Map<String,Object> map) {

        try {
            //获取文件流
            ClassPathResource resource = new ClassPathResource(tempPath);
            InputStream in = resource.getInputStream();
            response.setHeader("Content-Disposition", "inline;");
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName+".pdf", "UTF-8"));
            JasperPrint jasperPrint = JasperFillManager.fillReport(in, map, new JREmptyDataSource());
            JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static void printToImage(HttpServletResponse response, String tempPath, Map<String,Object> map, List list,String imgPath){

        try {

            //jar包这样读文件流。
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources(tempPath);
            Resource resource = resources[0];

            InputStream in = resource.getInputStream();
            JasperReport jasperReport = JasperCompileManager.compileReport(in);

            JRDataSource dataSource = new JRBeanCollectionDataSource(list);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map,dataSource );

            // 创建graphics输出器
            JRGraphics2DExporter exporter = new JRGraphics2DExporter();
            // 创建一个影像对象
            BufferedImage bufferedImage = new BufferedImage(jasperPrint.getPageWidth() * 4,
                    jasperPrint.getPageHeight() * 4, BufferedImage.TYPE_INT_RGB);
            // 取graphics
            Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
            // 设置相应参数信息
            exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, g);
            exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, Float.valueOf(4));
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.exportReport();
            g.dispose();// 释放资源信息
            // 这里的bufferedImage就是最终的影像图像信息,可以通过这个对象导入.
            ImageIO.write(bufferedImage, "JPEG", new File(imgPath));

            in.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
